package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;

import com.woyao.core.model.GetMyRelationResponse;
import com.woyao.core.model.RelationSearch;
import com.woyao.core.model.RelationSummary;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class MyRelationActivity extends AppCompatActivity {

    private List<RelationSummary> items = new ArrayList<RelationSummary>();
    private RelationAdapter allAdapter;
    private RecyclerView alllist = null;
    LinearLayoutManager allLayoutManager = null;

    private Integer RELATION_CODE = 100;

    ProgressDialog progressDialog;

    private String keyword = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_relation);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout



        Intent intent = getIntent();

        keyword = intent.getStringExtra("keyword") ;
        if ( keyword == null )
            keyword = "";


        alllist = (RecyclerView)findViewById(R.id.items);
        allLayoutManager = new LinearLayoutManager(this);
        allLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        alllist.setLayoutManager(allLayoutManager);
        alllist.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        loadData( keyword);

        this.registerForContextMenu(alllist);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }


    private AsyncTask<Void,Void,GetMyRelationResponse> task = null;
    private void loadData( final String kw){
        if(task != null)return;

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        task =new AsyncTask<Void, Void, GetMyRelationResponse>() {
            @Override
            protected GetMyRelationResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyRelationResponse> responseCall = svc.getMyRelation(userId,"",0);
                try {
                    GetMyRelationResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyRelationResponse response) {
                progressDialog.dismiss();
                render(response);
                task = null;
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }
    private void render(GetMyRelationResponse response){

        RelationSearch reletionList = response.getContent();
        items = reletionList.getItems();
        this.setTitle( reletionList.getTitle() );


        allAdapter = new RelationAdapter(this,  response.getContent().getItems() );

        allAdapter.setChangedHandler(new RelationAdapter.Changed() {
            @Override
            public void view(RelationSummary r, View v) {
                getIt(r.getId() );
            }


        });

        alllist.setAdapter(allAdapter);

    }

    private void getIt( final Integer curid ){
        Intent intent = new Intent();
        intent.setClass(MyRelationActivity.this, RelationActivity.class);
        intent.putExtra("id", curid  );
//        intent.setClass(MyRelationActivity.this, TalkActivity.class);
//        intent.putExtra("mid", curid  );
        startActivityForResult(intent,RELATION_CODE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RELATION_CODE ) {
            Boolean ischanged = data.getBooleanExtra("changed", true);
            if (ischanged) {
                loadData(keyword);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
